#define _CRT_SECURE_NO_WARNINGS 1
#include <cstdio>
#include <cstdlib>
#include <ctime>
#include <iostream>
using namespace std;
void CreateNDate()
{
	// 造数据
	int n = 10000;
	srand(time(0));
	const char* file = "data.txt";
	FILE* fin = fopen(file, "w");
	if (fin == NULL)
	{
		perror("fopen error");
		return;
	}

	for (size_t i = 0; i < n; ++i)
	{
		int x = rand() % 1000000;
		fprintf(fin, "%d\n", x);
	}

	fclose(fin);
}
void AdjustDown(int* _a, int n, int parent) {
    int child = (parent * 2 + 1); // 计算儿子节点
    while(child < n) // 循环条件
    {
        if(child + 1 < n && _a[child] > _a[child + 1]) // 找到更大的那一个
        {
            child++;
        }
        if(_a[child] < _a[parent]) // 交换对应的值
        {
            int temp = _a[parent];
            _a[parent] = _a[child];
            _a[child] = temp;
            parent = child;
            child = (parent * 2 + 1);
        }else // 条件不满足退出即可（注意）
        {
            break;
        }
    }
}
void PrintTopK(int k) {
    const char* file = "data.txt";
    FILE* fout = fopen(file, "r");
    if(fout == nullptr) {
        perror("fopen error");
        return;
    }
    int* minheap = (int*)malloc(sizeof(int) * k);
    if(minheap == nullptr) {
        perror("malloc error");
        return;
    }
    for(int i = 0; i < k; i++) {
        fscanf(fout, "%d", &minheap[i]);
    }
    for(int i = (k - 2) / 2; i >= 0; i--) {
        AdjustDown(minheap, k, i);
    }
    int val = 0;
    while(!feof(fout)) {
        fscanf(fout, "%d", &val);
        if(val > minheap[0]) {
            minheap[0] = val;
            AdjustDown(minheap, k, 0);
        }
    }
    for(int i = 0; i < k; i++) {
        printf("%d ", minheap[i]);
    }
}

int main() {
    CreateNDate();
    PrintTopK(20);
    return 0;
}